#!/bin/bash

# 配置部分
NEW_REGISTRY_URL="new-harbor.example.com"     # 新镜像仓库地址
DOCKER_USER="your-docker-username"             # Docker 用户名
DOCKER_PASSWORD="your-docker-password"         # Docker 密码

# 登录新的 Harbor 镜像仓库
echo "Logging in to the new Harbor registry..."
echo "$DOCKER_PASSWORD" | docker login "$NEW_REGISTRY_URL" -u "$DOCKER_USER" --password-stdin

# 获取所有镜像的列表
echo "Fetching Docker images..."
IMAGES=$(docker images --format "{{.Repository}}:{{.Tag}}")

# 筛选与 Rancher 相关的镜像
RANCHER_IMAGES=$(echo "$IMAGES" | grep 'rancher')

if [ -z "$RANCHER_IMAGES" ]; then
  echo "No Rancher images found."
  exit 0
fi

# 批量处理每个 Rancher 相关的镜像
for IMAGE in $RANCHER_IMAGES; do
  # 获取镜像的仓库和标签
  IMAGE_REPO=$(echo "$IMAGE" | awk -F':' '{print $1}')
  IMAGE_TAG=$(echo "$IMAGE" | awk -F':' '{print $2}')

  # 构建新的镜像名称
  NEW_IMAGE="$NEW_REGISTRY_URL/$(echo "$IMAGE_REPO" | awk -F'/' '{print $NF}'):$IMAGE_TAG"

  # 给镜像打标签
  echo "Tagging $IMAGE as $NEW_IMAGE..."
  docker tag "$IMAGE" "$NEW_IMAGE"

  # 上传镜像到新的 Harbor 镜像仓库
  echo "Pushing $NEW_IMAGE to the new Harbor registry..."
  docker push "$NEW_IMAGE"
done

# 完成后退出登录
echo "Logging out from the new Harbor registry..."
docker logout "$NEW_REGISTRY_URL"

echo "All Rancher images have been uploaded successfully."
